package com.ermax.aircond.util.listener;

import java.io.Serializable;

import org.hibernate.envers.EntityTrackingRevisionListener;
import org.hibernate.envers.RevisionType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import com.ermax.aircond.util.domain.AuditedRevEntity;

@Service("auditedListener")
public class AuditedListener implements EntityTrackingRevisionListener {

	public void newRevision(Object revisionEntity) {

	}

	@Override
	public void entityChanged(@SuppressWarnings("rawtypes") Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, Object revisionEntity) {

		AuditedRevEntity revEntity = (AuditedRevEntity) revisionEntity;

		String username = "SYSTEM";
		if (SecurityContextHolder.getContext() != null 
				&& SecurityContextHolder.getContext().getAuthentication() != null				
				&& SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
			
			UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			username = userDetails.getUsername();
		}
		revEntity.setUsername(username);
	}

}
